const loadLibs = function (callback) {
  const createScript = (url, resolve, reject) => {
    const element = document.createElement("script");
    element.src = url;
    element.onload = () => {
      console.log(url + "加载完成");
      resolve();
    }; // 当资源加载完成时，解决Promise
    element.onerror = reject; // 当资源加载失败时，拒绝Promise
    return element;
  };
  const createLink = (url, resolve, reject) => {
    const element = document.createElement("link");
    element.rel = "stylesheet";
    element.href = url;
    element.onload = () => {
      console.log(url + "加载完成");
      resolve();
    };
    element.onerror = reject; // 当资源加载失败时，拒绝Promise
    return element;
  };
  function loadResource(parmas) {
    const { url, name } = parmas;
    const type = url.split(".")[[url.split(".").length - 1]];
    return new Promise((resolve, reject) => {
      let element;
      // 创建一个新的<script>或<link>元素
      if (type === "js" || type === "com") {
        if (name) {
          if (!window[name]) {
            element = createScript(url, resolve, reject);
          } else {
            console.log(name + "加载完成");
            resolve();
          }
        } else {
          element = createScript(url, resolve, reject);
        }
      } else {
        element = createLink(url, resolve, reject);
      }

      // 将元素添加到文档中以开始加载
      document.head.appendChild(element);
    });
  }

  // 要加载的资源数组
  const resources = [
    {
      url: "https://cdn.staticfile.net/jquery/3.7.1/jquery.min.js",
      name: "jQuery",
    },
    {
      url: "https://cdn.staticfile.net/lodash.js/4.17.21/lodash.core.min.js",
      name: "_",
    },
    {
      url: "https://cdn.staticfile.net/bootstrap/5.3.2/css/bootstrap.min.css",
    },
    {
      url: "https://cdn.staticfile.net/bootstrap/5.3.2/js/bootstrap.min.js",
    },
    {
      url: "https://cdn.staticfile.net/interact.js/1.10.26/interact.min.js",
    },
    {
      url: "https://cdn.tailwindcss.com",
    },
  ];

  Promise.all(resources.map((item) => loadResource(item))).then(() => {
    console.log("全部加载完成");
    callback();
  });
};
